import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  SimpleChange,
  SimpleChanges
} from "@angular/core";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";

declare var $: any;

@Component({
  selector: "my-table",
  template: `
    <div class="tableRoom">
      <table [id]="o.tableid" [style.minWidth]="tableminwidth"></table>
    </div>
  `,
  styles: [
    ".tableRoom{overflow-x: auto}"
  ]
})
export class MytableComponent implements OnInit, OnChanges, OnDestroy {
  $table: any;
  lock: any;
  tableminwidth: string = "auto";

  inittable(): void {
    const that = this;
    const hastable = this.$table.children().length;
    if (hastable) {
      this.$table.bootstrapTable("refresh");
      return;
    }

    this.$table.bootstrapTable({
      classes: "table table-bordered",
      locale: "zh-CN",
      headerStyle: function () {
        if (that.o.headeraligncenter) {
          return {
            css: {'text-align': 'center'},
          }
        } else {
          return {
            css: {'text-align': 'left'},
          }
        }
      },
      virtualScroll: true,
      silentSort: false,
      pagination: this.o.pagination ? false : true,
      sidePagination: this.o.sidePagination,
      hiddenPageinfoLink: this.o.hiddenPageinfoLink,
      paginationLoop: this.o.paginationLoop ? false : true,
      paginationPreText: this.o.paginationPreText,
      paginationNextText: this.o.paginationNextText,
      pageNumber: 1,
      pageSize: this.o.pageSize,
      pageList: this.o.pageList,
      method: "post",
      cache: false,
      contentType: 'application/json;utf-8',
      queryParamsType: "undefined",
      sortName: this.o.sortName ? this.o.sortName : "",
      sortOrder: this.o.sortOrder ? this.o.sortOrder : "asc",
      height: this.o.height,
      detailViewIcon: this.o.detailViewIcon ? this.o.detailViewIcon : false,
      detailView: this.o.detailView ? this.o.detailView : false,
      detailFormatter: this.o.detailFormatter,
      ajax: function (param) {
        // 使用表格组件的加获取数据的加载效果（portlet 右上角的按钮等不能操作）
        that.commservice.blockUI({
          target: ".loadData",
          boxed: true,
          message: "数据获取中...",
          zIndex: 10051,
          overlayColor: "#67809F"
        });
        const url = that.o.url;
        const reqobj = that.o.reqobj;
        const nowreqobj = {};
        // 服务端分页
        if (that.o.sidePagination === "server") {
          nowreqobj["pageNum"] = param.data.pageNumber;
          nowreqobj["pageSize"] = param.data.pageSize;
          nowreqobj["pxlm"] = param.data.sortName;
          nowreqobj["pxfs"] = param.data.sortOrder;
        } else {
          //客户端分页，没有 pageNum 和 pageSize
          //nowreqobj["pxlm"] = param.data.sortName;
          //nowreqobj["pxfs"] = param.data.sortOrder;
        }


        if (reqobj != null) {
          const keys = Object.keys(reqobj);
          keys.forEach((key) => {
            nowreqobj[key] = reqobj[key];
          });
        }
        that.commservice.info("表格的请求数据", url, nowreqobj);
        that.itservice.kwPtPost(url, nowreqobj).subscribe(resp => {
          that.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
            // 去掉获取数据效果
            that.commservice.unblockUI(".loadData");
            if (flag) {
              if (flag2) {
                if (that.o.sidePagination === "server") {
                  const addxh_obj = {};
                  addxh_obj[that.o.total] = resp[that.o.total];
                  addxh_obj[that.o.rows] = resp[that.o.rows].map((item, index) => {
                    item["ordernum"] = (param.data.pageNumber - 1) * param.data.pageSize + index + 1;
                    return item;
                  });
                  param.success(addxh_obj);
                } else {
                  const tableid = that.o.tableid;
                  switch (tableid) {
                    case "table_kdfprs": {
                      const resultdataArr = resp.kdfpjgList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(resultdataArr);
                      // 客户端分页，考点分配结果 回传
                      that.outhander.emit({
                        tableid: tableid,
                        caozuo: "kdfp",
                        row: resultdataArr
                      });
                    }
                      break;
                    case "table_kcfprs": {
                      const resultdataArr = resp.kcfpjgList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(resultdataArr);
                      // 客户端分页，考点分配结果 回传
                      that.outhander.emit({
                        tableid: tableid,
                        caozuo: "kcfp",
                        row: resultdataArr
                      });
                    }
                      break;
                    case "table_kscc": {
                      const ksccList = resp.ksccList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(ksccList);
                    }
                      break;
                    case "table_bmsry":
                      const bmsGzryList = resp.bmsGzryList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(bmsGzryList);
                      break;
                    case "table_car":
                      const ysclManagerList = resp.ysclManagerList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(ysclManagerList);
                      break;
                    case "table_xjfagl":
                      const xjfaZyList = resp.xjfaZyList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(xjfaZyList);
                      break;
                    case "table_ntpfw":
                      const ntpList = resp.ntpfwqList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(ntpList);
                      break;
                    case "table_kcdy":
                      const kcdylist = resp.tjyglkcslList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(kcdylist);
                      break;
                    case "table_jkrysbtj":
                      const jkrysbtjlist = resp.ysbkwrysllList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(jkrysbtjlist);
                      break;
                    case "table_ywal":
                      const kswjals = resp.kswjals.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(kswjals);
                      break;
                    case "table_tjzs":
                      const rctjList = resp.rctjList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(rctjList);
                      break;
                    case "table_pjd":
                      const pjdZyLb = resp.pjdZyLb.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(pjdZyLb);
                      break;
                    case "table_pjjsk":
                      const pjlslb = resp.pjlslb.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(pjlslb);
                      break;
                    case "table_hclist":
                      const hclb = resp.hclb.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(hclb);
                      break;
                    case "table_templatecl":
                      const clList = resp.clList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(clList);
                      break;
                    case "table_qbperson":
                    case "table_qbpersontxl":
                      const csgzryList = resp.csgzryList.map((item, index) => {
                        item["ordernum"] = index + 1;
                        return item
                      });
                      param.success(csgzryList);
                      break;
                    default: {
                      param.success(resp);
                    }
                  }
                }
              } else {
                that.commservice.myswal("warning", resp, "", "ts", null);
                // 获取表格数据时候，业务逻辑错误
                if (that.o.sidePagination === "server") {
                  const ywerrobj = {};
                  ywerrobj[that.o.total] = 0;
                  ywerrobj[that.o.rows] = [];
                  param.success(ywerrobj);
                } else if (that.o.sidePagination === "client") {
                  param.success([]);
                }
              }
            } else {
              that.inittable();
            }
          })
        });
      },
      totalField: this.o.total,
      dataField: this.o.rows,
      columns: this.o.columns,
      clickToSelect: this.o.clickToSelect ? this.o.clickToSelect : false,
      onClickRow: function (row, $element, field) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onClickRow",
          row: row
        })
      },
      onCheck: function (row, $element) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onCheck",
          row: row,
          index: $element.data("index")
        })
      },
      onPostBody: function (data) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onPostBody",
          data: data
        })
      },
      onUncheck: function (row, $element) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onUncheck",
          row: row,
          index: $element.data("index")
        })
      },
      onCheckAll: function (row, $element) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onCheckAll",
          row: row,
        })
      },
      onUncheckAll: function (row, $element) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onUncheckAll",
          row: $element,
        })
      },
      onExpandRow: function (index, row, $detail) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onExpandRow",
          row: row,
        })
      },
      onCollapseRow: function (index, row, detailView) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onExpandRow",
          row: row,
        })
      },
      onSort: function (name, order) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onSort",
          data: {
            sortname: name,
            sortorder: order
          },
        })
      },
      onLoadSuccess: function (e) {
        that.outhander.emit({
          tableid: that.o.tableid,
          caozuo: "onLoadSuccess",
          data: {
            resp: e,
          },
        })
      }
    });
  }

  /**
   * tableid ----渲染表格的id
   * url ----远程服务器资源
   * reqobj ----除了 pageSize pageNum外的， 没有传null
   * height----头部固定滚动要求的，有此属性
   * pagination ---不传递，使用表格默认配置值表示表格要分页， 传递true,则表格不分页
   * sidePagination--client/server
   * pageSize----初始化每页的数据条数
   * pageList ----没页数据条数的控制下拉值
   * total----接口返回的 total的别名
   * rows----接口返回的 rows的别名
   * columns--表格的column
   * sortName---表格初始化要排序的列  --默认 undefined
   * sortOrder---表格初始化排序应用的排序规则  --默认 asc
   * tableminwidth--- 默认auto,表格最小宽度
   * hiddenPageinfoLink ---默认false，显示除了上一页下一页外的，快捷导航。  true--只显示上一页下一页
   * paginationLoop ---不传递，使用表格默认配置，循环。   传递true,表示不循环
   * paginationPreText---默认是 <
   * paginationNextText---默认是    >
   * headeraligncenter---默认left,传递true,则表头标居中
   * detailView---设置父子表,设置true为显示详细视图表。
   * detailViewIcon---设置true为显示详细信息视图列（加/减图标）
   * detailFormatter---
   */
  @Input() o: any;
  @Output() outhander: EventEmitter<any> = new EventEmitter<any>();

  constructor(private commservice: CommService,
              private itservice: MyhttpService) {

  }

  ngOnInit() {
    this.lock = setInterval(() => {
      if ($("#" + this.o.tableid).length) {
        clearInterval(this.lock);
        this.$table = $("#" + this.o.tableid);
        this.tableminwidth = this.o.tableminwidth ? `${this.o.tableminwidth}px` : "auto";
        this.inittable();
      }
    }, 100);
  }

  ngOnChanges(changes: { [hs: string]: SimpleChange }) {
    const firstchange = changes.o.firstChange;
    if (!firstchange) {
      this.commservice.log('mytable---ngOnChanges--o', this.o);
      this.commservice.log("mytable---ngOnChanges", changes.o.currentValue === this.o);
      this.inittable();
    }
  }

  ngOnDestroy() {
    if (this.lock) {
      clearInterval(this.lock);
    }
  }

}
